<?php defined('SYSPATH') or die('No direct script access.');

class Model_Shop
{
	public function getAllCategory()
	{
		$categorys = ORM::factory('shopcategory')->find_all();
		
		$i = 0;
		foreach($categorys as $k => $v)
		{
			$array[$i]['id']	= $v->id;
			$array[$i]['name']	= $v->name;
			$i++;
		}
		
		return $array;
	}
	
	
	public function getProductsByCategory($categorytId)
	{
		$products = ORM::factory('shopproduct')->where('idCategory', '=', $categorytId)->find_all();
		$array = array();
		
		$i = 0;
		foreach($products as $k => $v)
		{
			$array[$i]['id']			= $v->id;
			$array[$i]['name']			= $v->name;
			$array[$i]['description']	= $v->description;
			$array[$i]['photo']			= $v->photo;
			$array[$i]['price']			= $v->price;
			$i++;
		}
		
		
		return $array;
	}
	
	
	public function getProducts()
	{
		$products = ORM::factory('shopproduct')->find_all();
		
		$i = 0;
		foreach($products as $k => $v)
		{
			$array[$i]['id']			= $v->id;
			$array[$i]['name']			= $v->name;
			$array[$i]['description']	= $v->description;
			$array[$i]['photo']			= $v->photo;
			$array[$i]['price']			= $v->price;
			$i++;
		}
		
		
		return $array;
	}
	
	public function getProduct($productId)
	{
		
		$products = ORM::factory('shopproduct')->where('id', '=', $productId)->find();
		
		$array['id']			= $products->id;
		$array['name']			= $products->name;
		$array['description']	= $products->description;
		$array['photo']			= $products->photo;
		$array['price']			= $products->price;
		
		
		
		return $array;
	}
	
	
	public function newOrder($products, $userId = 1)
	{
		$shoporder		= ORM::factory('shoporder');
		$shopshopping	= ORM::factory('shopshopping');
		//$shopproduct	= ORM::factory('shopproduct');
		
		$price = 0;
		foreach($products as $product)
		{
			$a = ORM::factory('shopproduct')->where('id', '=', $product['productId'])->find();
			
			$price += $a->price;
		}
		
		//$shoporder->id		= '';
		$shoporder->userId	= $userId;
		$shoporder->price		= $price;
		$lastOrder = $shoporder->save();
		
		
		
		foreach($products as $product)
		{
			$a = ORM::factory('shopproduct')->where('id', '=', $product['productId'])->find();
			
			$shopshopping->orderId		= $lastOrder;
			$shopshopping->productId	= $product['productId'];
			$shopshopping->count		= $product['productCount'];
			$shopshopping->price		= $a->price;
			$shopshopping->save()->clear();
		}
		
		
		return $lastOrder;
	}
	
	
	public function getPriceByOrder($orderId)
	{
		$a = ORM::factory('shoporder')->where('id', '=', $orderId)->find();
		
		$array['id']		= $a->id;
		$array['userId']	= $a->userId;
		$array['price']		= $a->price;
		
		return $array;
	}
	
	
	public function getCountOrdersByUser($userId)
	{
		$a = ORM::factory('shoporder')->where('userId', '=', $userId)->find_all();
		
		return count($a); 
	}
	
} // End Shop
